/*
 * @Description:
 * @version:
 * @Author: 潘骏杰
 * @Date: 2021-11-19 09:03:57
 * @LastEditors: 潘骏杰
 * @LastEditTime: 2021-12-24 17:00:22
 */
import axios from 'axios'
import { Notify } from 'vant'
import RSA from '@/utils/rsa.js'
import CryptoJS from '@/utils/CryptoJS'
import sha1 from 'js-sha1'
// import router from "@/router";

const baseURL =
  process.env.NODE_ENV === 'development' ? '/api' : window.productionUrl
// const baseURL = '/api'
// console.log(process.env)
// 创建axios实例
const service = axios.create({
  baseURL, // api的base_url  window.productionUrl
  withCredentials: true,
  timeout: 30000 // 请求超时时间
})

// 发送请求拦截器
service.interceptors.request.use(
  (config) => {
    config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    if (window.localStorage.getItem('appKey')) {
      window.appKey = window.localStorage.getItem('appKey')
      window.appsecret = 'pgykou9tl6c5es73bmfw47s0qxm6eijp'
    } else {
      window.appKey = '81g777ajqo8lk7cy2uiyedf5gf855ssd1'
      window.appsecret = 'opkjjs7wb6c5ee12xxfw23d0rxd5eqwe'
    }
    const Nonce =
      Math.ceil(+new Date() / 1000) + '' + Math.ceil(Math.random() * 10000)
    const CurTime = Math.floor(+new Date() / 1000).toString()
    config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    const appsecret = window.appsecret
    let hasTokenObj
    // console.log(hasTokenObj);
    const sureHas = window.localStorage.getItem('loginToken') || undefined
    if (sureHas && window.localStorage.getItem('loginPersonMsg')) {
      console.log(sureHas)
      hasTokenObj = JSON.parse(CryptoJS.decrypt(sureHas))
      // console.log(hasTokenObj);
    }
    if (hasTokenObj) {
      // console.log("有");
      config.headers['Authorization'] =
        hasTokenObj.tokeType + ' ' + hasTokenObj.accessToken
      config.headers['nonce'] = Nonce
      config.headers['curTime'] = CurTime
      config.headers['ReqUseAlgo'] = 'base64'
      console.log(appsecret + Nonce + CurTime + 'base64')
      config.headers['checkSum'] = sha1(appsecret + Nonce + CurTime + 'base64')

      const params = config.data
      console.log(JSON.stringify(params))
      console.log('AES加密')
      const jiami = CryptoJS.encrypt(JSON.stringify(params))
      console.log(jiami)
      config.data = jiami
      return config
    } else {
      // console.log("无");

      config.headers['appKey'] = window.appKey
      const params = config.data
      console.log(JSON.stringify(params))
      console.log('RSA加密')
      const jiami = RSA.encrypt(JSON.stringify(params))
      console.log(jiami)
      config.data = jiami
      return config
    }
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 发送请求响应拦截
service.interceptors.response.use(
  (response) => {
    // console.log(response.data);
    const res = response.data
    if (window.localStorage.getItem('loginToken')) {
      return CryptoJS.decrypt(res)
    } else if (res.result) {
      console.log(res.body)
      return CryptoJS.decrypt(res.body)
    } else {
      Notify({ type: 'danger', message: res.message || 'error' })
      return Promise.reject(res.message || 'error')
    }
    // if (res.status !== 200) {

    //   router.go(-1);
    //   // 其他的code 需要单独判断
    //   //       //501 token匹配失败，回到登录

    //   // if (response.code == 501) {
    //   //   // ??? 需要单独调试一番
    //   //   store.dispatch('user/backToLogin').then(() => {
    //   //     //location.reload()
    //   //   })
    //   // }

    //   return Promise.reject(res.message || "error");
    // } else {

    // }
  },
  (error) => {
    // console.log("err" + error);
    // if (error.response.status == 500) {
    //   location.reload()
    // }
    Notify({ type: 'danger', message: error.message || 'error' })
    return Promise.reject(error)
  }
)

export default service
